<template>
  <div class="app-container">
    <el-card
      class="filter-container"
      shadow="never"
    >
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small"
        >
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form
          :inline="true"
          :model="listQuery"
          size="small"
          label-width="140px"
        >
          <el-form-item label="机构名称：">
            <el-input
              v-model="listQuery.deptName"
              class="input-width"
              placeholder="机构名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select
              v-model="listQuery.status"
              placeholder="全部"
              clearable
              class="input-width"
            >
              <el-option
                v-for="(item,index) in typeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card
      class="operate-container"
      shadow="never"
    >
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button
        size="mini"
        class="btn-add"
        @click="handleAdd()"
      >新增机构</el-button>
    </el-card>
    <div class="table-container">
      <el-table
        ref="adminTable"
        :data="list1"
        style="width: 100%;"
        v-loading="listLoading"
        border
      >
        <el-table-column
          label="机构名称"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.deptName }}</template>
        </el-table-column>
        <el-table-column
          label="合同开始时间"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.startTime | formatDateTime }}</template>
        </el-table-column>
        <el-table-column
          label="合同结束时间"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.endTime | formatDateTime }}</template>
        </el-table-column>
        <el-table-column
          label="状态"
          align="center"
        >
          <template slot-scope="scope">{{ status[scope.row.status] }}</template>
        </el-table-column>
        <el-table-column
          label="场馆数量"
          width="140"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.siteCount }}</template>
        </el-table-column>
        <el-table-column
          label="联系人"
          width="140"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.contactsName }}</template>
        </el-table-column>
        <el-table-column
          label="联系电话"
          width="140"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.phone }}</template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="260"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="goToVen(scope.$index, scope.row)"
            >
              场馆管理
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="goToInst(scope.$index, scope.row)"
            >
              机构服务
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="del(scope.$index, scope.row)"
              v-if="scope.row.status=='02'"
            >
              冻结
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="del(scope.$index, scope.row)"
              v-if="scope.row.status=='03'&&(isWithinTheTerm (scope.row.startTime, scope.row.endTime))||(scope.row.status=='04'&&isWithinTheTerm (scope.row.startTime, scope.row.endTime))"
            >
              激活
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="umsDeptGet(scope.$index, scope.row)"
            >
              查看
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.$index, scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit?'编辑数据':'新增数据'"
      :visible="dialogVisible"
      @close="closedialogVisible"
      width="40%"
    >
      <el-form
        :model="admin"
        :rules="rules"
        ref="courseFrom"
        label-width="150px"
        size="small"
      >
        <el-form-item
          label="机构名称："
          prop="deptName"
        >
          <el-input
            v-model="admin.deptName"
            class="input-width"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="合作时间："
          prop="dateRange"
          required
        >
          <el-date-picker
            v-model="admin.dateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dateRangeChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="机构地址："
          prop="deptAddr"
          required
        >
          <el-input
            v-model="admin.deptAddr"
            class="input-width"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="联系人："
          prop="contactsName"
        >
          <el-input
            v-model="admin.contactsName"
            class="input-width"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="联系电话："
          prop="phone"
        >
          <el-input
            v-model="admin.phone"
            class="input-width"
          ></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="closedialogVisible"
          size="small"
        >取 消</el-button>
        <el-button
          type="primary"
          @click="handleDialogConfirm()"
          size="small"
        >确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="备注"
      :visible.sync="dialog"
      width="60%"
    >
      <el-form
        :model="listQuery"
        ref="reasonForm"
        label-width="180px"
        :rules="rules1"
      >
        <el-form-item
          label="请输入冻结/激活原因："
          prop="remarks"
        >
          <el-input
            class="input-width"
            v-model="listQuery.remarks "
          ></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleConfirm"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { curCourseTypeList, commonListLB } from '@/api/login'
import {
  umsServDeptList,
  updateDept,
  saveDept,
  updateaStatus
} from '@/api/servDept'
import { formatDate } from '@/utils/date'
import moment from 'moment'

const defaultListQuery = {
  pageNum: 1,
  pageSize: 10
}
const umsData = {
  contactsName: 'string',
  createTime: '2020-09-16T13:04:42.871Z',
  deptAddr: 'string',
  deptName: 'string',
  endTime: '2020-09-16T13:04:42.871Z',
  id: 0,
  phone: 'string',
  remarks: 'string',
  siteCount: 0,
  startTime: '2020-09-16T13:04:42.871Z',
  status: 'string',
  updateTime: '2020-09-16T13:04:42.871Z'
}
export default {
  name: 'AdminList',
  data () {
    return {
      daterange: [],
      row: {},
      dialog: false,
      status2: '',
      list1: [],
      id: 0,
      courseTypeOptions: '',
      addUms: false,
      deptType: '',
      deptRangeList: [],
      typeOptions: [
        { value: '01', label: '未合作' },
        { value: '02', label: '合作中' },
        { value: '03', label: '已停止' },
        { value: '04', label: '冻结' }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      value: [],
      options: [],
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      admin: Object.assign({}, umsData),
      isEdit: false,
      status: {
        '01': '未合作',
        '02': '合作中',
        '03': '已停止',
        '04': '冻结'
      },
      count: 1,
      rules: {
        deptName: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur'
          }
        ],
        dateRange: [{ required: true, message: '请选择', trigger: 'blur' }],
        deptAddr: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      rules1: {
        remarks: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getList()
    commonListLB().then((response) => {
      const list = response.data
      list.map((item) => {
        const { id, commonCode, commonDesc } = item
        const listB = {
          id: id,
          value: parseInt(commonCode),
          label: commonDesc
        }
      })
    })

    curCourseTypeList().then((response) => {
      const list = response.data.list
      this.courseTypeOptions = response.data.list
      let a = 0
      let listB = {}
      list.map((item) => {
        const { id, typeName, subset } = item
        const children = []
        if (subset) {
          subset.map((i) => {
            const { id, typeName } = i
            const listA = {
              id: id,
              value: id,
              label: typeName,
              parentId: a
            }
            children.push(listA)
          })
        }
        if (subset) {
          listB = {
            id: id,
            value: id,
            label: typeName,
            children: children
          }
        } else {
          listB = {
            id: id,
            value: id,
            label: typeName
          }
        }

        this.options.push(listB)
        a = a + 1
      })
    })
  },
  filters: {
    formatDateTime (time) {
      if (time == null || time === '') {
        return 'N/A'
      }
      const date = new Date(time)
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    }
  },
  methods: {
    getDateStr (time) {
      const date = time ? new Date(time) : new Date()
      return formatDate(date, 'yyyyMMddhhmmss')
    },
    isWithinTheTerm (startTime, endTime) {
      return (
        this.getDateStr() > this.getDateStr(startTime) &&
        this.getDateStr() < this.getDateStr(endTime)
      )
    },
    dateRangeChange (e) {
      this.admin.startTime = moment(e[0]).format()
      this.admin.endTime = moment(e[1]).format()
    },
    handleAdd () {
      this.admin = {
        cityName: '北京'
      }
      // this.$router.push({ path: '/dept-ms/addServDept' })
      this.dialogVisible = true
      this.isEdit = false
      this.addUms = true
    },
    closedialogVisible () {
      this.dialogVisible = false
      this.addUms = false
    },
    handleDialogConfirm () {
      this.$refs['courseFrom'].validate((valid) => {
        if (valid) {
          this.listLoading = true
          const params = this.admin
          params.id = this.admin.id

          if (!this.addUms) {
            updateDept(params).then((response) => {
              this.dialogVisible = false
              this.listLoading = false
              this.$message({
                message: response.message,
                type: 'success'
              })
              this.addUms = false
              this.getList()
            })
          } else {
            this.admin.cityCode = 1
            saveDept(params).then((response) => {
              this.dialogVisible = false
              this.listLoading = false
              this.$message({
                message: response.message,
                type: 'success'
              })
              this.addUms = false
              this.getList()
            })
          }
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    handleChange (value) {},
    handleResetSearch () {
      this.listQuery = Object.assign({}, defaultListQuery)
      this.deptRangeList = []
    },
    handleSearchList () {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleSizeChange (val) {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    umsDeptGet (index, row) {
      this.$router.push({
        path: '/dept-ms/detailServDept',
        query: { id: row.id }
      })
    },
    goToVen (index, row) {
      this.$router.push({
        path: '/dept-ms/deptVen',
        query: { id: row.id, deptName: row.deptName }
      })
    },
    goToInst (index, row) {
      this.$router.push({
        path: '/dept-ms/deptInst',
        query: { deptId: row.id, name: row.deptName }
      })
    },
    handleUpdate (index, row) {
      this.admin = Object.assign(this.admin, row)
      this.$set(this.admin, 'dateRange', [this.admin.startTime, this.admin.endTime])
      this.row = row
      this.dialogVisible = true
      this.isEdit = true
      this.addUms = false
      this.getList()
    },
    del (index, row) {
      this.row = row
      this.dialog = true
      this.$set(this.listQuery, 'remarks', '')

    },
    handleConfirm () {
      this.$refs['reasonForm'].validate((valid) => {
        if (valid) {
          if (this.row.status === '02') {
            const data = {
              status: '04',
              id: this.row.id,
              remarks: this.listQuery.remarks
            }
            // this.listQuery.note = "";
            updateaStatus(data).then(() => {
              this.$message({
                message: '冻结成功！',
                type: 'success'
              })
              this.dialog = false
              this.getList()
            })
          } else if (this.row.status === '03' || this.row.status === '04') {
            const data = {
              status: '02',
              id: this.row.id,
              remarks: this.listQuery.remarks
            }
            // this.listQuery.note = "";
            updateaStatus(data).then(() => {
              this.$message({
                message: '激活成功！',
                type: 'success'
              })
              this.dialog = false
              this.getList()
            })
          }
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    getList () {
      this.listLoading = true
      umsServDeptList(this.listQuery).then((response) => {
        this.listLoading = false
        this.list = response.data.list.map((item) => {
          item.cityName = '北京'
          return item
        })
        this.total = response.data.total
        this.list1 = this.list.map((item) => {
          var status1 = item.status
          item.status_val = this.status[status1]
          return item
        })
      })
    }
  }
}
</script>
<style>
.el-date-editor .el-range-separator {
  padding: 0 5px;
  /*line-height: 32px;*/
  width: 15%;
  color: #303133;
}
.el-date-editor--daterange.el-input__inner {
  width: 100%;
}
</style>
